package com.yex.utils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Author: 袁晓钧
 * @Date: Created in 2018/2/1 16:24
 * @Version: V1
 * @Description:
 */
public class FileUtil {



    public static boolean savePhotoFile(String dir, String fileName, InputStream inputStream, String uploadDir) {
        boolean flag = false;
        File directory = new File(dir);

        if (!directory.exists()) {
            directory.mkdirs();
        }
        if (!directory.isDirectory()) {
            return flag;
        }

        if (inputStream == null) {
            return false;
        }
        File realFile = new File(directory, fileName);
        BufferedImage bufferedImage = null;
        try {
            bufferedImage = ImageIO.read(inputStream);
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            if (width != height) {
                if(width>height){
                    //裁宽
                    bufferedImage = ImgUtils.cropImage(bufferedImage, (width - height) / 2, 0, (width - height) / 2 + height, height);
                }else{
                    //裁高
                    bufferedImage=ImgUtils.cropImage(bufferedImage,0,(height-width)/2,width,(int) (height-width)/2+width
                    );
                }
            }
            ImageIO.write(bufferedImage, fileName.split("\\.")[1], realFile);
            flag = true;
        } catch (IOException e) {
            flag = false;
        } finally {
            bufferedImage.flush();
        }
        return flag;
    }


}
